package com.lbd.finance.controller;

import com.lbd.commons.Constants;
import com.lbd.finance.bean.WebTradeDetail;
import com.lbd.finance.bean.vo.ExportWebTradeDetailVo;
import com.lbd.finance.bean.vo.WebTradeDetailVo;
import com.lbd.finance.service.WebTradeDetailService;
import com.lbd.base.controller.BaseController;
import com.lbd.commons.Result;
import com.lbd.commons.ResultState;
import com.lbd.system.service.DictionaryService;
import com.lbd.util.ExcelExportUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import com.lbd.base.controller.BaseController;
import com.lbd.commons.Result;
import com.lbd.commons.ResultState;
import com.lbd.finance.bean.WebTradeDetail;
import com.lbd.finance.service.WebTradeDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 平台交易记录
 */
@RestController
@RequestMapping("/webTradeDetail")
public class WebTradeDetailController extends BaseController {
    private final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private WebTradeDetailService webtradedetailService;
    @Autowired
    private DictionaryService dictionaryService;

    /**
     * 时间筛选条件格式，重新定义
     * @param webDataBinder
     * @throws Exception
     */
//	@InitBinder
//	public void initBinder(WebDataBinder webDataBinder) throws Exception{
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		sdf.setLenient(false);
//		webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true));
//	}

    /**
     * 按条件分页查询webtradedetail
     *
     * @param page           第几页
     * @param rows           一页多少条
     * @param webtradedetail
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(int page, int rows, WebTradeDetailVo webtradedetail) {
        //更新网站可用余额
        //可用余额为非实时更新，每次查询时，进行更新
        //1、查找未进行正确更新的记录，
        //2、查找已经更新统计过的可用余额。
        //3、按照交易时间进行更新可用余额
        List<WebTradeDetail> webTradeDetails = webtradedetailService.findAllByNotStatistic();
        if (CollectionUtils.isNotEmpty(webTradeDetails)) {
            BigDecimal balance = webtradedetailService.findByStatistic();
            for (WebTradeDetail detail : webTradeDetails) {
                if (detail.getTrdDirec() == Constants.TRD_DIRECT_1) {
                    balance = balance.add(detail.getTrdAmt());
                } else {
                    balance = balance.subtract(detail.getTrdAmt());
                }
                detail.setBalance(balance);
                detail.setIsStatistic(true);
                webtradedetailService.update(detail);
            }

        }


        return new Result(ResultState.SUCCESS, "查询成功", webtradedetailService.findByPageConditionJpql(page, rows, webtradedetail));
    }

    /**
     * 保存webtradedetail信息
     *
     * @param webtradedetail
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Result save(WebTradeDetail webtradedetail) {
        webtradedetailService.save(webtradedetail);
        return new Result(ResultState.SUCCESS, "添加成功", "");
    }

    /**
     * 根据id查询回显要编辑的WebTradeDetail
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public Result toEdit(String id) {
        return new Result(ResultState.SUCCESS, "加载成功", webtradedetailService.findById(id));
    }

    /**
     * 修改webtradedetail信息
     *
     * @param webtradedetail
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result update(WebTradeDetail webtradedetail) {
        webtradedetailService.update(webtradedetail);
        return new Result(ResultState.SUCCESS, "更新成功");
    }

    /**
     * 导出网站收支信息
     *
     * @param request        request
     * @param response       response
     * @param webTradedetail 查询条件
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, WebTradeDetailVo webTradedetail) {

        List<WebTradeDetail> webTradeDetailList = webtradedetailService.findByConditionJpql(webTradedetail);
        //处理数据字典信息
        String keys = Constants.DIC_WEBTRADE_TYPE;
        Map<String, Map<String, String>> dictionaryMap = dictionaryService.getDictionary(keys);
        List<ExportWebTradeDetailVo> webTradeDetailVoList = new ArrayList<>();
        ExportWebTradeDetailVo webTradeDetailVo;
        for (WebTradeDetail tradeDetail : webTradeDetailList) {
            webTradeDetailVo = new ExportWebTradeDetailVo();
            try {
                BeanUtils.copyProperties(webTradeDetailVo, tradeDetail);
            } catch (IllegalAccessException | InvocationTargetException e) {
                log.info("导出网站支出信息执行copy时出现异常：");
                log.info(e);
            }
            if (null != tradeDetail.getTrdDirec()) {
                webTradeDetailVo.setTrdDirecName(tradeDetail.getTrdDirec() == Constants.TRD_DIRECT_1 ? "收入" : "支出");
            }
            webTradeDetailVo.setTrdTypeName(dictionaryMap.get(Constants.DIC_WEBTRADE_TYPE).get(tradeDetail.getTrdType().toString()));
            webTradeDetailVo.setTrdTimeStr(DateFormatUtils.format(tradeDetail.getTrdTime(), "yyyy-MM-dd HH:mm:ss"));
            webTradeDetailVoList.add(webTradeDetailVo);
        }

        ExcelExportUtils.exportExcel(request, response, DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"), ExportWebTradeDetailVo.class, webTradeDetailVoList);

    }


}
